package com.ssm.oss.controller;
import com.google.common.base.Preconditions;
import com.ssm.oss.entity.Result;
import com.ssm.oss.service.FileService;
import lombok.extern.log4j.Log4j2;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;

@RestController
@Log4j2
public class FileController {
    @Resource //根据名称注入
    private FileService fileService;

    /**
     * 上传文件, 返回文件在oss中的地址
     * @param uploadFile:文件, getOriginalFilename获取原始文件名
     * @param bucket：桶名称
     * @param objectName：上传后的文件在存储桶中的存储路径(存储目录)
     * @return String: 返回文件在minio的链接地址
     */
    @PostMapping("/upload")
    public Result<String> upload(MultipartFile uploadFile, String bucket, String objectName) throws Exception {
        try {
            Preconditions.checkArgument(!ObjectUtils.isEmpty(uploadFile), "文件不能为空");
            Preconditions.checkArgument(!StringUtils.isEmpty(bucket), "bucket桶名称不能为空");
            if(log.isInfoEnabled()) {
                log.info("FileController.upload.uploadFile:{}, bucket:{}, objectName:{}", uploadFile.getOriginalFilename(), bucket, objectName);
            }
            String url = fileService.uploadFile(uploadFile, bucket, objectName);
            return Result.ok(url);
        } catch (Exception e) {
            log.info("FileController.upload.error：{}", e.getMessage(), e);
            return Result.fail("上传文件失败");
        }
    }

}
